#=================================
#Paper title: Taking a Gamble: Chinese Overseas Energy Finance and Country Risk
#Authors: Hanna Niczyporuk (NYU) and Johannes Urpelainen (JOHNS HOPKINS SAIS) 

#Last modified: December 3, 2020

#Purpose: Generate figures used in the paper 
#Remark: First set up your working directory (here abbreviated as 'workingdirectory')
#Data used: barplot2.csv

####################################################################################################################

#First load all packages

library(foreign)
library(doBy)
library(ggplot2)
library(sf)
library(raster)
library(spData)
library(dplyr)
library(tidyr)  
library(xtable)
library(stringr)
library(xlsx)
library(writexl)

####################################################################################################################

# Figures used in the main paper:

####################################################################################################################

# Fig. 1. Investment by MDBs (2005–2017)

####################################################################################################################

bardata <- read.csv("~/workingdirectory/barplot2.csv", header=TRUE, strip.white = TRUE)
bardata$X <- NULL
bardata$count <- NULL
bardata$mdb_finance_bln_usd <- NULL
bardata$perc_projects <- NULL

bardata2 <- bardata %>% mutate(energy_source = str_replace(energy_source, "Solar, wind and biomass", "Renewables"))

figure1 <- ggplot(data=bardata2, aes(x=mdb, y=perc_amount, fill=energy_source)) +
  geom_bar(stat="identity",width = 0.9)+
  labs(x = "Multilateral Development Bank") + labs(y = "Share in the Energy Investment Portfolio (%)")  + labs(fill = "Energy Source") +
  scale_fill_brewer(palette="Blues")+
  theme_minimal() +
  theme(legend.position="bottom")
figure1
ggsave("~/workingdirectory/figure1.pdf")

####################################################################################################################

# Fig. 2. Map of the investment by Chinese banks (2005–2017)

####################################################################################################################

#Load investment dataset

geci <- read.csv("~/workingdirectory/geci_noenergysources_orig_nocontrols.csv", header=TRUE, strip.white = TRUE)
geci <- filter(geci, year<2018)
geci <- filter(geci, 2004<year)
geci <- geci %>%
  group_by(country) %>% 
  summarise(mdb_finance_bln_usd = sum(mdb_finance_bln_usd), count = sum(count))


#Load ISO/countryname dataset and merge it with the investment dataset
iso3 <- read.csv("~/workingdirectory/iso3.csv", header=TRUE, strip.white = TRUE)
geci<- left_join(geci, iso3, by="country")
geci$count <- NULL
geci$country <- NULL
#geci$mdb_finance_mln_usd <- geci$mdb_finance_bln_usd * 1000
#geci$log_finance_usd <- log(geci$mdb_finance_usd)
#geci$mdb_finance_bln_usd <- NULL
#geci$mdb_finance_usd <- NULL

#Create a heatmap
mapped_data <- joinCountryData2Map(geci, joinCode = "ISO3", nameJoinColumn = "countrycode") 
new_world <- subset(mapped_data, continent != "Antarctica")
#par(mai=c(0,0,0.2,0),xaxs="i",yaxs="i")

colourPalette <- brewer.pal(7,'Blues')
map1 <- mapCountryData(new_world, mapTitle ="", nameColumnToPlot ="mdb_finance_bln_usd",colourPalette=colourPalette,  catMethod=c(0,1, 10, 20, 30, 40, 50))

do.call( addMapLegend, c(map1
                         , legendLabels="all"
                         , legendWidth=0.5 ))
map1

ggsave("~/workingdirectory/figure2.pdf")

rm(list = ls())

####################################################################################################################

# Fig. 3. Investment by Chinese and non-Chinese banks by credit and governance risks (2005–2017)

####################################################################################################################

china <- read_xlsx("china_pol.xlsx")
world <- read_xlsx("world.xlsx")
nonchina <- read_xlsx("nonchina_pol.xlsx")
install.packages("gtable")
library(gridExtra)

#Credit Rating

#China:

rankorig_china <- dplyr::select(china, country,rankorig,mdb_finance_bln_usd)
rankorig_china <- na.omit(rankorig_china)
rankorig_china <- rankorig_china%>% 
  group_by(country) %>% 
  summarise(rankorig = mean(rankorig), finance=sum(mdb_finance_bln_usd))
rankorig_china$country <- NULL

#Non-China:

rankorig_nonchina <- dplyr::select(nonchina, country,rankorig,mdb_finance_bln_usd)
rankorig_nonchina <- na.omit(rankorig_nonchina)

rankorig_nonchina <- rankorig_nonchina%>% 
  group_by(country) %>% 
  summarise(rankorig = mean(rankorig), finance=sum(mdb_finance_bln_usd))
rankorig_nonchina$country <- NULL

#World:

rankorig_world <- dplyr::select(world, country,rankorig)
rankorig_world <- na.omit(rankorig_world)

rankorig_world <- rankorig_world%>% 
  group_by(country) %>% 
  summarise(rankorig = mean(rankorig))
rankorig_world$country <- NULL
creditrank <-ggplot()+
  geom_density(data = rankorig_world, aes(x = rankorig, color='World'), linetype="dashed") + 
  geom_density(data = rankorig_china, aes(x = rankorig,weight=finance/sum(finance),color = 'China')) + 
  geom_density(data = rankorig_china, aes(x = rankorig,weight=finance/sum(finance)),fill="steelblue",alpha=0.8) + 
  geom_density(data = rankorig_nonchina, aes(x = rankorig,weight=finance/sum(finance),color = 'Non-China'), linetype="dashed") + 
  xlab("Credit Rating") + ylab("Density") +
  theme(legend.position = 'bottom') +
  scale_color_manual(values = c('World' = 'black', 'China' = 'steelblue','Non-China' = 'red'))+ 
  theme(legend.title = element_blank())
creditrank

#Corruption

#China:
corruption_china <- dplyr::select(china, country,corruption_rounded,mdb_finance_bln_usd)
corruption_china <- na.omit(corruption_china)

corruption_china <- corruption_china%>% 
  group_by(country) %>% 
  summarise(corruption_rounded = mean(corruption_rounded), finance=sum(mdb_finance_bln_usd))
corruption_china$country <- NULL
#Non-China:
corruption_nonchina <- dplyr::select(nonchina, country,corruption_rounded,mdb_finance_bln_usd)
corruption_nonchina <- corruption_nonchina[which(!is.na(corruption_nonchina$corruption_rounded)),]

corruption_nonchina <- corruption_nonchina%>% 
  group_by(country) %>% 
  summarise(corruption_rounded = mean(corruption_rounded), finance=sum(mdb_finance_bln_usd))
corruption_nonchina$country <- NULL

#World:
corruption_world <- dplyr::select(world, country , corruption_rounded)
corruption_world <- na.omit(corruption_world)

corruption_world <- corruption_world%>% 
  group_by(country) %>% 
  summarise(corruption_rounded = mean(corruption_rounded))
corruption_world$country <- NULL


corruption <-ggplot()+
  geom_density(data = corruption_world, aes(x = corruption_rounded, color='World'), linetype="dashed") + 
  geom_density(data = corruption_china, aes(x = corruption_rounded,weight=finance/sum(finance),color = 'China')) + 
  geom_density(data = corruption_china, aes(x = corruption_rounded,weight=finance/sum(finance)),fill="steelblue",alpha=0.8) + 
  geom_density(data = corruption_nonchina, aes(x = corruption_rounded,weight=finance/sum(finance),color = 'Non-China'), linetype="dashed") + 
  xlab("Corruption Index") + ylab("Density") +
  scale_x_continuous(limits = c(0, 1))+
  theme(legend.position = 'bottom') +
  scale_color_manual(values = c('World' = 'black', 'China' = 'steelblue','Non-China' = 'red'))+ 
  theme(legend.title = element_blank())
corruption

#Government Effectiveness

#China:
effectivegovernment_china <- dplyr::select(china, country,gov_effectiveness_rounded,mdb_finance_bln_usd)
effectivegovernment_china <- na.omit(effectivegovernment_china)

effectivegovernment_china <- effectivegovernment_china%>% 
  group_by(country) %>% 
  summarise(gov_effectiveness_rounded = mean(gov_effectiveness_rounded), finance=sum(mdb_finance_bln_usd))
effectivegovernment_china$country <- NULL

#Non-China:
effectivegovernment_nonchina <- dplyr::select(nonchina, country,gov_effectiveness_rounded,mdb_finance_bln_usd)
rankorig_china <- na.omit(rankorig_china)

effectivegovernment_nonchina <- effectivegovernment_nonchina%>% 
  group_by(country) %>% 
  summarise(gov_effectiveness_rounded = mean(gov_effectiveness_rounded), finance=sum(mdb_finance_bln_usd))
effectivegovernment_nonchina$country <- NULL
#World:
effectivegovernment_world <- dplyr::select(world, country , gov_effectiveness_rounded)
rankorig_china <- na.omit(rankorig_china)

effectivegovernment_world <- effectivegovernment_world%>% 
  group_by(country) %>% 
  summarise(gov_effectiveness_rounded = mean(gov_effectiveness_rounded))
effectivegovernment_world$country <- NULL

effectivegovernment <-ggplot()+
  geom_density(data = effectivegovernment_world, aes(x = gov_effectiveness_rounded, color='World'), linetype="dashed") + 
  geom_density(data = effectivegovernment_china, aes(x = gov_effectiveness_rounded,weight=finance/sum(finance),color = 'China')) + 
  geom_density(data = effectivegovernment_china, aes(x = gov_effectiveness_rounded,weight=finance/sum(finance)),fill="steelblue",alpha=0.8) + 
  geom_density(data = effectivegovernment_nonchina, aes(x = gov_effectiveness_rounded,weight=finance/sum(finance),color = 'Non-China'), linetype="dashed") + 
  xlab("Government Effectiveness Index") + ylab("Density") +
  scale_x_continuous(limits = c(0, 1))+
  theme(legend.position = 'bottom') +
  scale_color_manual(values = c('World' = 'black', 'China' = 'steelblue','Non-China' = 'red'))+ 
  theme(legend.title = element_blank())
effectivegovernment

grid.arrange(creditrank, corruption,  effectivegovernment, ncol=1, nrow =3)
ggsave("~/workingdirectory/figure3.pdf")

####################################################################################################################

# Fig. 4. Investment by Chinese and non-Chinese banks by political stability and regime type (2005–2017)

####################################################################################################################

#Political stability
#China:
politicalstability_china <- dplyr::select(china, country,political_stability_rounded,mdb_finance_bln_usd)
politicalstability_china <- na.omit(politicalstability_china)
politicalstability_china <- politicalstability_china%>% 
  group_by(country) %>% 
  summarise(political_stability_rounded = mean(political_stability_rounded), finance=sum(mdb_finance_bln_usd))
politicalstability_china$country <- NULL
#Non-China

politicalstability_nonchina <- dplyr::select(nonchina, country,political_stability_rounded,mdb_finance_bln_usd)
politicalstability_nonchina <- na.omit(politicalstability_nonchina)
politicalstability_nonchina <- politicalstability_nonchina%>% 
  group_by(country) %>% 
  summarise(political_stability_rounded = mean(political_stability_rounded), finance=sum(mdb_finance_bln_usd))
politicalstability_nonchina$country <- NULL
#World:
politicalstability_world <- dplyr::select(world, country , political_stability_rounded)
politicalstability_world <- na.omit(politicalstability_world)

politicalstability_world <- politicalstability_world%>% 
  group_by(country) %>% 
  summarise(political_stability_rounded = mean(political_stability_rounded))
politicalstability_world$country <- NULL

politicalstability <-ggplot()+
  geom_density(data = politicalstability_world, aes(x = political_stability_rounded, color='World'), linetype="dashed") + 
  geom_density(data = politicalstability_china, aes(x = political_stability_rounded,weight=finance/sum(finance),color = 'China')) + 
  geom_density(data = politicalstability_china, aes(x = political_stability_rounded,weight=finance/sum(finance)),fill="steelblue",alpha=0.8) + 
  geom_density(data = politicalstability_nonchina, aes(x = political_stability_rounded,weight=finance/sum(finance),color = 'Non-China'), linetype="dashed") + 
  xlab("Political Stability Index") + ylab("Density") +
  scale_x_continuous(limits = c(0, 1))+
  theme(legend.position = 'bottom') +
  scale_color_manual(values = c('World' = 'black', 'China' = 'steelblue','Non-China' = 'red'))+ 
  theme(legend.title = element_blank())
politicalstability

#Autocracy

#China
auto_china <- dplyr::select(china, year,auto_bin, invested)
auto_china <- na.omit(auto_china)
auto_china <- auto_china%>% 
  group_by(auto_bin) %>% 
  summarise(projects = sum(invested))
auto_china$share <- auto_china$projects/150
auto_china$region <- "Chinese Projects"
auto_china$projects <-NULL

#Non-China
auto_nonchina <- dplyr::select(nonchina, year,auto_bin, invested)
auto_nonchina <- na.omit(auto_nonchina)
auto_nonchina <- auto_nonchina%>% 
  group_by(auto_bin) %>% 
  summarise(projects = sum(invested))
auto_nonchina$share <- auto_nonchina$projects/1096
auto_nonchina$region <- "Non-Chinese Projects"
auto_nonchina$projects <-NULL

#World
auto_world <- dplyr::select(world, year,auto_bin, count)
auto_world <- na.omit(auto_world)
auto_world <- auto_world%>% 
  group_by(year,auto_bin) %>% 
  summarise(count = sum(count))

total <- auto_world%>% 
  group_by(year) %>% 
  summarise(countries = sum(count))
auto_world <- left_join(auto_world,total, by="year")
auto_world$share <- auto_world$count/auto_world$countries
auto_world <- auto_world%>% 
  group_by(auto_bin) %>% 
  summarise(share = mean(share))
auto_world$region <- "World"

autocracy_data <- rbind(auto_china,auto_nonchina,auto_world)
autocracy_data$perc <- round((autocracy_data$share*100),0)
autocracy_data$regime <- NULL
autocracy_data$regime[autocracy_data$auto_bin==1] <- "Autocracy"
autocracy_data$regime[autocracy_data$auto_bin==0] <- "Democracy"
autocracy_data$auto_bin <- NULL
autocracy_data$share <- NULL

autocracy <- ggplot(data=autocracy_data, aes(x=factor(regime), y=perc, fill = factor(region))) + 
  geom_bar(stat="identity", position = "dodge") +
  scale_y_continuous(limits = c(0, 70))+
  scale_fill_manual(values = c("#004C99", "steelblue","dodgerblue4"))+
  labs(y="Percentage Share")+
  theme(legend.title = element_blank())+
  labs(x="Regime Type")+
  geom_text(aes(label=paste(perc,"%")), position=position_dodge(width=0.9), vjust=-0.25)+ 
  theme(legend.position="bottom")
autocracy

grid.arrange(politicalstability, autocracy, ncol=1, nrow =2)
ggsave("~/workingdirectory/figure4.pdf")

####################################################################################################################

# Figures used in the appendix:

####################################################################################################################

# Fig. A2.1. Map of the investment by non-Chinese banks (2005–2017)

####################################################################################################################

#Load investment dataset

mdb <- read.csv("~/workingdirectory/mdb_noenergysources_orig_nocontrols.csv", header=TRUE, strip.white = TRUE)
mdb <- filter(mdb, year<2018)
mdb <- filter(mdb, 2004<year)

mdb<- filter(mdb, mdb!="GECI") 
mdb <- mdb %>%
  group_by(country) %>% 
  summarise(mdb_finance_bln_usd = sum(na.omit(mdb_finance_bln_usd)), count = sum(count))

#Load ISO/countryname dataset and merge it with the investment dataset
iso3 <- read.csv("~/workingdirectory/iso3.csv", header=TRUE, strip.white = TRUE)
mdb<- left_join(mdb, iso3, by="country")
mdb$count <- NULL
mdb$country <- NULL


#Create a heatmap
mapped_data <- joinCountryData2Map(mdb, joinCode = "ISO3", nameJoinColumn = "countrycode") 
new_world <- subset(mapped_data, continent != "Antarctica")
#par(mai=c(0,0,0.2,0),xaxs="i",yaxs="i")

colourPalette <- brewer.pal(7,'Blues')
map2 <- mapCountryData(new_world, mapTitle ="", nameColumnToPlot ="mdb_finance_bln_usd",colourPalette=colourPalette,  catMethod=c(0,1, 10, 20, 30, 40, 50))

do.call( addMapLegend, c(map2
                         , legendLabels="all"
                         , legendWidth=0.5 ))
map2


ggsave("~/workingdirectory/figurea21.pdf")

